﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
using LightSwitchApplication.UserCode;
using System.Linq.Expressions;
using System.Collections.ObjectModel;
using System.Threading;
namespace LightSwitchApplication
{
    public partial class SalesOrderDetail
    {
        partial void Quantity_Changed()
        {
            this.Amount = this.Quantity * this.Price;
        }

        partial void Price_Changed()
        {
            this.Amount = this.Quantity * this.Price;
        }

        partial void Amount_Changed()
        {
            if (this.VATInfo != null)
            {
                if (this.PercentTax != null)
                {
                    this.AmountAfterTax = this.Amount + this.Amount * this.PercentTax.Value / 100;
                    return;
                }
            }
            this.AmountAfterTax = this.Amount;
        }

        partial void PercentTax_Changed()
        {
            Amount_Changed();
        }

        partial void VATInfo_Changed()
        {
            if (this.VATInfo != null)
            {
                this.PercentTax = this.VATInfo.Percent;
            }
        }

        partial void InoxType_Changed()
        {
            GetPrice();
        }

        public void GetPrice()
        {
            if (this.Details.EntityState == EntityState.Unchanged) return;

            string _ItemID = !Uti.IsNull(this.Item) && !Uti.IsNull(this.Item.ItemID) ? this.Item.ItemID : "";
            string _ItemConfig = !Uti.IsNull(this.ItemConfig) && !Uti.IsNull(this.ItemConfig.ConfigID) ? this.ItemConfig.ConfigID : "";
            string _InoxType = !Uti.IsNull(this.InoxType) && !Uti.IsNull(this.InoxType.InoxID) ? this.InoxType.InoxID : "";
            string _ItemSize = !Uti.IsNull(this.ItemSize) && !Uti.IsNull(this.ItemSize.SizeID) ? this.ItemSize.SizeID : "";
            string _ItemOther = !Uti.IsNull(this.ItemOther) && !Uti.IsNull(this.ItemOther.OtherID) ? this.ItemOther.OtherID : "";
              
            var result = this.DataWorkspace.wcfServiceData.ExcuteStore6("GetLastPrice", _ItemID, _InoxType, _ItemConfig, _ItemSize, _ItemOther, "0").Execute();
            if (result.Count() > 0)
            {
                decimal price;
                if (decimal.TryParse(result.ElementAt(0).Result , out price) && (this.Price == null || this.Price.Value == 0))
                {
                    this.Price = price;
                }
            }
        }

        partial void ItemConfig_Changed()
        {
            GetPrice();
        }

        partial void ItemOther_Changed()
        {
            GetPrice();
        }

        partial void Item_Changed()
        {
            GetPrice();
        }

        partial void ItemSize_Changed()
        {
            GetPrice();
        }


    }
}
